package com.feilong.edgeAI.view;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2023/12/28 18:07
 */

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.ImageDecoder;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.adapter.AINetVoiceContentAdapter;
import com.feilong.edgeAI.adapter.CommadClassifyAdapter;
import com.feilong.edgeAI.adapter.RemindAdapter;
import com.feilong.edgeAI.model.AINetVoiceContentRespone;
import com.feilong.edgeAI.model.CommadClassify;
import com.feilong.edgeAI.model.FloatViewState;
import com.feilong.edgeAI.model.StartAIUI;
import com.feilong.edgeAI.model.ToastMsg;
import com.feilong.edgeAI.utils.MusicPlayer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.warkiz.tickseekbar.OnSeekChangeListener;
import com.warkiz.tickseekbar.SeekParams;
import com.warkiz.tickseekbar.TickSeekBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


public class GlobalFloatingView implements MusicPlayer.OnMusicPlayListener {
    public static final int ONLINE_AI = 1;
    public static final int OFFLINE_AI = 2;
    private static final String TAG = "GlobalFloatingView";
    private String gitPath = "file:///android_asset/xiaofei_gif.gif";
    private String xiaofei_gitPath = "file:///android_asset/xiaofei_gif.gif";
    private String xiaolong_gitPath = "file:///android_asset/xiaolong_gif.gif";
    private Context context;
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private View view;
    private View layout;
    private View interactiveLayout;
    private View playLayout;
    private View confirmView;
    private AnimatedRecordingView waveView;
    private ImageView imageView;
    //    private GifImageView imageView;
    private EditText askView;
    private TextView answerView;
    private TextView recognitionView;
    private ImageView playBtn;
    private TickSeekBar tickSeekBar;

    private MusicPlayer musicPlayer;

    private ImageView gifImage;

    private RecyclerView voiceRecyclerView;

    private AINetVoiceContentAdapter mAINetVoiceContentAdapter;

    private List<AINetVoiceContentRespone> voiceData;

    public GlobalFloatingView(Context context) {
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.float_voice_layout, null);
        waveView = view.findViewById(R.id.waveview);
        imageView = view.findViewById(R.id.voice_icon);
        gifImage = view.findViewById(R.id.iv_gif);
        layout = view.findViewById(R.id.layout);
        playLayout = view.findViewById(R.id.play_layout);
        askView = view.findViewById(R.id.ask_view);
        tickSeekBar = view.findViewById(R.id.seekbar);
        playBtn = view.findViewById(R.id.play_btn);
        interactiveLayout = view.findViewById(R.id.interactive_layout);
        answerView = view.findViewById(R.id.answer_view);
        answerView.setMovementMethod(ScrollingMovementMethod.getInstance());
        recognitionView = view.findViewById(R.id.recognition_view);
        confirmView = view.findViewById(R.id.confirm);
        askView.setFocusable(true);
        askView.setFocusableInTouchMode(true);
        voiceRecyclerView = view.findViewById(R.id.voice_recyclerView);
        askView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d(TAG, "onFocusChange: " + hasFocus);
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    if (hasFocus) {

                        if (onClickFloatListener != null) {
                            onClickFloatListener.onShowEdit();
                        }
                        showSoftKeyboard();
                    } else {
                        hideSoftKeyboard();
                    }
                }
            }
        });
        askView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals(askText)) {
                    confirmView.setVisibility(View.GONE);
                } else {
                    confirmView.setVisibility(View.VISIBLE);
                }
            }
        });
        confirmView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmView.setVisibility(View.GONE);
                askView.clearFocus();
                hideSoftKeyboard();
                if (onClickFloatListener != null) {
                    onClickFloatListener.onTextChanged(askView.getText().toString().trim());
                }
            }
        });
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hide();
                if (null != onClickFloatListener) {
                    onClickFloatListener.onDimiss();
                }
            }
        });
        interactiveLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != onClickFloatListener) {
                    onClickFloatListener.onVoiceBtnClick();
                }
            }
        });
        musicPlayer = new MusicPlayer(context);
        musicPlayer.setOnMusicPlayListener(this);
        tickSeekBar.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {

            }

            @Override
            public void onStartTrackingTouch(TickSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(TickSeekBar seekBar) {
                musicPlayer.setProgress(seekBar.getProgress());
            }
        });
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (musicPlayer.isPlaying()) {
                    musicPlayer.resume();
                    playBtn.setImageResource(R.mipmap.pause_icon);
                } else {
                    playBtn.setImageResource(R.mipmap.play_icon);
                    musicPlayer.pause();
                }
            }
        });
        init();
        answerView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 获取TextView中的文本
                String text = answerView.getText().toString();

                // 获取剪贴板管理器
                ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                if (clipboard != null) {
                    // 创建一个剪贴数据对象并设置要复制的文本
                    ClipData clip = ClipData.newPlainText("label", text);
                    // 将剪贴数据对象复制到剪贴板
                    clipboard.setPrimaryClip(clip);

                    // 可以添加一个Toast或者其他提示来告知用户复制成功
                    ToastUtils.showShort(context.getString(R.string.copyed));
                }

                return true; // 返回true表示已处理长按事件
            }
        });
        voiceData = new ArrayList<>();
        mAINetVoiceContentAdapter = new AINetVoiceContentAdapter(context, voiceData);
        voiceRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        voiceRecyclerView.setAdapter(mAINetVoiceContentAdapter);
//        if (0 == SPUtils.getInstance().getInt("ai_toggle")) {
            //imageView.setVisibility(View.VISIBLE);
//        }
    }

    // 显示软键盘的方法
    public void showSoftKeyboard() {
        if (null == askView) return;
        answerView.setText("");
        InputMethodManager imm = (InputMethodManager) askView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(askView, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    // 隐藏软键盘的方法
    public void hideSoftKeyboard() {
        if (null == askView) return;
        InputMethodManager imm = (InputMethodManager) askView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(askView.getWindowToken(), 0);
        }
    }

    public void playMusic(String path) {
        musicPlayer.playLocalMusic(path);
        playBtn.setImageResource(R.mipmap.pause_icon);
        playLayout.setVisibility(View.VISIBLE);
        recognitionView.setText("");
        answerView.setText("");
        Log.d(TAG, "playMusic setAnswerViewText: ");
        interactiveLayout.setVisibility(View.VISIBLE);
    }

    private String askText;

    public void setAskViewText(String text) {
        askText = text;
        askView.setText(text);
        Log.d(TAG, "setAskViewText: " + text);
        interactiveLayout.setVisibility(View.VISIBLE);
        confirmView.setVisibility(View.GONE);
    }

    public void setAnswerViewText(String text) {

        Log.d(TAG, "setAnswerViewText: " + text);
        recognitionView.setText("");
        interactiveLayout.setVisibility(View.VISIBLE);
        playLayout.setVisibility(View.GONE);
        confirmView.setVisibility(View.GONE);
        answerView.setText(text);
    }

    //    public void setVoiceData(List<AINetVoiceContentRespone> data) {
//        voiceData.clear();
//        voiceData = new ArrayList<>();
//        voiceData.addAll(data);
//        mAINetVoiceContentAdapter.addAll(voiceData);
//        mAINetVoiceContentAdapter.notify();
//    }
    public void setVoiceData(List<AINetVoiceContentRespone> data) {
        voiceData = new ArrayList<>();
        mAINetVoiceContentAdapter = new AINetVoiceContentAdapter(context, data);
        voiceRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        voiceRecyclerView.setAdapter(mAINetVoiceContentAdapter);
    }

    public void cleanVoiceData() {
        voiceData = new ArrayList<>();
        mAINetVoiceContentAdapter = new AINetVoiceContentAdapter(context, voiceData);
        voiceRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        voiceRecyclerView.setAdapter(mAINetVoiceContentAdapter);
    }


    public void hideInteractiveLayout() {
        interactiveLayout.setVisibility(View.GONE);
    }

    public void setRecognitionText(String text) {
        recognitionView.setText(text);
        askView.setText("");
        answerView.setText("");
        Log.d(TAG, "setRecognitionText setAnswerViewText: ");
        interactiveLayout.setVisibility(View.GONE);
    }

    private void init() {
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, // 使用适当的窗口类型
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN, // 窗口标志
                PixelFormat.TRANSLUCENT); // 窗口透明度格式
//        layoutParams = new WindowManager.LayoutParams();
//        layoutParams.width  = WindowManager.LayoutParams.MATCH_PARENT;
//        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
//        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

        // 系统级别的窗口
//        layoutParams.type =  WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
//        windowManager.addView(view, layoutParams);
    }

    private boolean isShow;

    public boolean isShowing() {
        return isShow;
    }

    public void show() {
        if (view != null) {
            if (view.getWindowToken() == null) {
                windowManager.addView(view, layoutParams);
                isShow = true;
                interactiveLayout.setVisibility(View.GONE);
                EventBus.getDefault().post(new FloatViewState(true));
            } else {
                Log.d(TAG, "show: removeView");
                windowManager.removeView(view);
                isShow = false;
                EventBus.getDefault().post(new FloatViewState(false));
            }
        }

    }

    public void setVolume(int volume) {
//        Log.d("TAG", "setVolume: "+volume);
        waveView.setVolume(volume);
    }

    public void hide() {
        if (view != null && view.getWindowToken() != null) {
            Log.d(TAG, "hide: removeView");
            windowManager.removeView(view);
            isShow = false;
            EventBus.getDefault().post(new FloatViewState(false));
            EventBus.getDefault().post(new FloatViewState(false));
            EventBus.getDefault().post(new StartAIUI());
        }
    }

    public void awakeModel(int type) {
        waveView.setVisibility(View.GONE);
//        if (OFFLINE_AI == SPUtils.getInstance().getInt("ai_mode")) {
//            imageView.setVisibility(View.VISIBLE);
//        }
//        imageView.setVisibility(View.VISIBLE);
        waveView.stop();

        if (0 == SPUtils.getInstance().getInt("ai_toggle")) {
            imageView.setVisibility(View.GONE);
            gitPath = xiaofei_gitPath;
        } else {
            imageView.setVisibility(View.GONE);
            //imageView.setVisibility(View.VISIBLE);
            gitPath = xiaolong_gitPath;
        }
        Glide.with(context)
                .asGif()
                .load(gitPath) // 指定GIF文件路径
                .diskCacheStrategy(DiskCacheStrategy.NONE) // 不缓存到磁盘
                .into(gifImage);
    }

    public void recognitionModel() {
        waveView.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.GONE);
        waveView.start();
        recognitionView.setText(R.string.listening);

    }

    private OnClickFloatListener onClickFloatListener;

    public void setOnClickFloatListener(OnClickFloatListener onClickFloatListener) {
        this.onClickFloatListener = onClickFloatListener;
    }

    @Override
    public void onProgress(int progress) {
        if (null != tickSeekBar) {
            tickSeekBar.setProgress(progress);
        }
    }

    @Override
    public void onCompletion() {
        if (null != onClickFloatListener) {
            Log.d(TAG, "onCompletion: ");
            onClickFloatListener.onPlayEnd();
        }
    }

    public interface OnClickFloatListener {
        void onVoiceBtnClick();


        void onDimiss();


        void onPlayEnd();

        void onTextChanged(String text);

        void onShowEdit();
    }
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThread(ToastMsg command) throws RemoteException {
//        ToastUtils.showShort("主人，问题正在计算……");
//    }

//    public void showToast(){
//        ToastUtils.showShort("主人，问题正在计算……");
//    }

    public void showToast() {
        waveView.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.GONE);
        waveView.start();
        recognitionView.setText("主人，请稍等，上一个问题正在计算……");
    }
}